﻿namespace ChumChase.FriendFeed
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows;
    using DefaultFeeds;
    using Extensions;
    using global::FriendFeed;
    using Model;
    using Services;
    using Views;

    public class FriendFeedProvider : IFeedProvider
    {
        private readonly IList<IFeedIdentity> _defaultFeeds = new List<IFeedIdentity>();
        private readonly IList<DataTemplate> _templates = new List<DataTemplate>();
        private FriendFeedClient _client;
        private FriendFeedSettings _settings = new FriendFeedSettings();

        public FriendFeedProvider()
        {
            _templates.AddDataTemplateFor<FeedEntry, FeedEntryTemplate>();
            _templates.AddDataTemplateFor<FriendFeedSettings, SettingsTemplate>();

            _defaultFeeds.Add(new HomeFeed());
        }

        public void ApplySettings()
        {
            _client = new FriendFeedClient(_settings.Nickname, _settings.RemoteKey);
        }

        public IFeedProviderSettings Settings
        {
            get { return _settings; }
        }

        public string DisplayName
        {
            get { return "FriendFeed"; }
        }

        public IEnumerable<DataTemplate> DataTemplates
        {
            get { return _templates; }
        }

        public IEnumerable<IFeedEntry> GetEntriesFor(string feedId)
        {
            if (_client == null) return new List<IFeedEntry>();

            IEnumerable<FeedEntry> entries = from entry in _client.FetchHomeFeed().Entries
                                             select new FeedEntry
                                                        {
                                                            Id = entry.Id,
                                                            Service = "FriendFeed:" + entry.Service.Name,
                                                            CreatedOn = entry.Published,
                                                            Title = entry.Title,
                                                        };

            return entries.Cast<IFeedEntry>();
        }

        public void LoadSettings(ILocalStorage storage)
        {
            _settings = storage.Load<FriendFeedSettings>(_settings.DetermineFileName()) ?? new FriendFeedSettings();
        }

        public void SaveSettings(ILocalStorage storage)
        {
            storage.Save(_settings, _settings.DetermineFileName());
        }

        public IEnumerable<IFeedIdentity> DefaultFeeds
        {
            get { return _defaultFeeds; }
        }
    }
}